package com.ruoyi.feike.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.ruoyi.activiti.domain.dto.ActTaskDTO;
import com.ruoyi.activiti.domain.vo.SearchVo;
import com.ruoyi.common.core.page.CustomPage;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.vo.*;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.feike.service.IDealerNegativeInformationCheckService;
import com.ruoyi.feike.service.IFileuploadService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.identity.UserGroupManager;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.runtime.shared.security.SecurityManager;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.model.payloads.GetTasksPayload;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricDetail;
import org.activiti.engine.history.HistoricVariableUpdate;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.activiti.runtime.api.model.impl.APITaskConverter;
import org.activiti.runtime.api.query.impl.PageImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * feikeService业务层处理
 *
 * @author ruoyi
 * @date 2022-07-07
 */
@Service
public class AnnualReviewyServiceImpl implements IAnnualReviewyService {
    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;

    @Autowired
    private BasicInformationMapper basicInformationMapper;

    @Autowired
    private DetailInformationMapper detailInformationMapper;

    @Autowired
    private DealerInformationMapper dealerInformationMapper;

    @Autowired
    private WholesalePerformanceCurrentlyMapper wholesalePerformanceCurrentlyMapper;

    @Autowired
    private WholesalePerformanceRecentThreeMonthsMapper wholesalePerformanceRecentThreeMonthsMapper;

    @Autowired
    private SalesPerformanceAndTargetMapper salesPerformanceAndTargetMapper;

    @Autowired
    private LimitCalculationForCommericalNeedsMapper limitCalculationForCommericalNeedsMapper;

    @Autowired
    private OtherFinancingResourceMapper otherFinancingResourceMapper;

    @Autowired
    private TemporaryConditionFollowUpMapper temporaryConditionFollowUpMapper;

    @Autowired
    private ProposalByCommericalAndMarketingMapper proposalByCommericalAndMarketingMapper;

    @Autowired
    private SecuritiesMapper securitiesMapper;

    @Autowired
    private NotesMapper notesMapper;

    @Autowired
    private CreditConditionMapper creditConditionMapper;

    @Autowired
    private ApprovedLimitAndConditionMapper approvedLimitAndConditionMapper;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IDealerNegativeInformationCheckService dealerNegativeInformationCheckService;

    @Autowired
    private TaskRuntime taskRuntime;

    @Autowired
    private UserGroupManager userGroupManager;

    @Autowired
    private SecurityManager securityManager;

    @Autowired
    private APITaskConverter taskConverter;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private SysUserMapper userMapper;


    @Autowired
    private IFileuploadService fileuploadService;


    /**
     * 查询feike
     *
     * @param id feikeID
     * @return feike
     */
    @Override
    public Map<String, Object> selectAnnualReviewyById(String id) {
        Map<String, Object> map = new HashMap<>();  //一级
        AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyById(id);
        if (annualReviewy != null) {
            map.put("id", annualReviewy.getId()); // id
            map.put("instanceId", annualReviewy.getInstanceId()); // instanceId
            map.put("title", annualReviewy.getTitle()); // 标题
            map.put("createTime", annualReviewy.getCreateTime()); // 创建时间
            map.put("createName", annualReviewy.getCreateName()); // 发起人中午名称
            map.put("createBy", annualReviewy.getCreateBy()); // 发起人用户名称
        }
        Map<String, Object> data = new HashMap<>();  // 二级
        List<Map<String, Object>> childrenList = new ArrayList();
        Map<String, Object> groupName = new HashMap<>();
        Map<String, Object> children = new HashMap<>();

        // List<BasicInformation> basicInformationList = basicInformationMapper.selectDealerGroupByByInstanceId(annualReviewy.getInstanceId());
        // if (basicInformationList != null && basicInformationList.size() > 0) {
        //     for (BasicInformation basicInformation : basicInformationList) {
        //         groupName.put("groupNameEN", basicInformation.getGroupNameEN()); // groupNameEN
        //         groupName.put("groupNameCN", basicInformation.getGroupNameCN()); // groupNameCN
        //     }
        // }
        List<BasicInformation> basicInformationList = basicInformationMapper.selectDealerGroupByByInstanceId(annualReviewy.getInstanceId());
        if (basicInformationList != null && basicInformationList.size() > 0) {
            for (BasicInformation basicInformation : basicInformationList) {
                groupName.put("groupNameEN", basicInformation.getGroupNameEN()); // groupNameEN
                groupName.put("groupNameCN", basicInformation.getGroupNameCN()); // groupNameCN

                children.put("basicInformationId", basicInformation.getId());
                children.put("instanceId", basicInformation.getInstanceId());
                children.put("GM", basicInformation.getGm());
                children.put("dealerCodeFromManufacturer", basicInformation.getDealerCodeFromManufacturer());
                children.put("dealerCodeFromWFS", basicInformation.getDealerCodeFromWFS());
                children.put("dealerNameCN", basicInformation.getDealerNameCN());
                children.put("dealerNameEN", basicInformation.getDealerNameEN());
                children.put("dealername", basicInformation.getDealername());
                children.put("incorporationDate", basicInformation.getIncorporationDate());
                children.put("joinSectorDealerNetworkDate", basicInformation.getJoinSectorDealerNetworkDate());
                children.put("paidupCapital", basicInformation.getPaidupCapital());
                children.put("province", basicInformation.getProvince());
                children.put("relatedWorkingExperience", basicInformation.getRelatedWorkingExperience());
                children.put("value", basicInformation.getDealerValue());

                String[] split = basicInformation.getSector().split(",");
                children.put("sector", split);
                children.put("shareholdersAndShare", basicInformation.getShareholders());
            }
        }
        data.put("groupName", groupName); // groupNameEN
        // Map<String, Object> children = new HashMap<>();
        List<SalesPerformanceAndTarget> salesPerformanceAndTargetList = salesPerformanceAndTargetMapper.selectSalesPerformanceAndTargetByInstanceId(annualReviewy.getInstanceId());
        if (salesPerformanceAndTargetList != null && salesPerformanceAndTargetList.size() > 0) {
            children.put("sales_performance_and_target", salesPerformanceAndTargetList);
        }

        List<LimitCalculationForCommericalNeeds> limitCalculationForCommericalNeedList = limitCalculationForCommericalNeedsMapper.selectLimitCalculationForCommericalNeedsByInstanceId(annualReviewy.getInstanceId());
        if (limitCalculationForCommericalNeedList != null && limitCalculationForCommericalNeedList.size() > 0) {
            children.put("limit_calculation_for_commerical_needs", limitCalculationForCommericalNeedList);
        }

        List<OtherFinancingResource> otherFinancingResourceList = otherFinancingResourceMapper.selectOtherFinancingResourceByInstanceId(annualReviewy.getInstanceId());
        if (otherFinancingResourceList != null && otherFinancingResourceList.size() > 0) {
            children.put("other_financing_resource", otherFinancingResourceList);
        }

        List<TemporaryConditionFollowUp> temporaryConditionFollowUpList = temporaryConditionFollowUpMapper.selectTemporaryConditionFollowUpByInstanceId(annualReviewy.getInstanceId());
        if (temporaryConditionFollowUpList != null && temporaryConditionFollowUpList.size() > 0) {
            children.put("temporary_condition_follow_up", temporaryConditionFollowUpList);
        }

        List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketingList = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingByInstanceId(annualReviewy.getInstanceId());
        if (proposalByCommericalAndMarketingList != null && proposalByCommericalAndMarketingList.size() > 0) {
            children.put("proposal_by_commerical_and_marketing", proposalByCommericalAndMarketingList);
        }

        List<Securities> securitieList = securitiesMapper.selectSecuritiesByInstanceId(annualReviewy.getInstanceId());
        if (securitieList != null && securitieList.size() > 0) {
            children.put("securities", securitieList);
        }
        childrenList.add(children);
        data.put("children", childrenList);
        Notes notes = notesMapper.selectNotesByInstanceId(annualReviewy.getInstanceId());
        if (notes != null) {
            data.put("basicNotes", notes.getBasicNotes());
            data.put("dealerNotes", notes.getDealerNotes());
            data.put("loyaltyNotes", notes.getLoyaltyNotes());
            data.put("auditNotes", notes.getAuditNotes());
            data.put("wholesaleNotes", notes.getWholesaleNotes());
            data.put("proposalNotes", notes.getProposalNotes());
        }
        map.put("data", data);
        return map;
    }

    /**
     * 查询feike列表
     *
     * @param annualReviewy feike
     * @return feike
     */
    @Override
    public List<AnnualReviewyHistoryVO> selectAnnualReviewyList(AnnualReviewy annualReviewy, BasicInformation basicInformation) {
        return annualReviewyMapper.selectAnnualReviewyListBySelf(annualReviewy, basicInformation, SecurityUtils.getLoginUser()
                .getUser()
                .getDeptId());
    }

    /**
     * 新增feike
     *
     * @param map feike
     * @return 结果
     */
    @Override
    @Transactional
    //public int insertAnnualReviewy(AnnualReviewy annualReviewy)
    public int insertAnnualReviewy(Map<String, Object> map) {
        String instanceId = IdUtils.simpleUUID();
        String title = "";
        if (StringUtils.isNotNull(map.get("name"))) {
            title = SecurityUtils.getLoginUser().getUser().getNickName() + "-" + map.get("name");
        } else {
            title = SecurityUtils.getLoginUser().getUser().getNickName() + "-" + "年审流程";
        }


        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                .getUser()
                .getUserId()
                .toString());
        ProcessInstance processInstance = null;
        if (StringUtils.isNotNull(map.get("processDefinitionKey"))) {
            processInstance = processRuntime.start(ProcessPayloadBuilder
                    .start()
                    .withProcessDefinitionKey(map.get("processDefinitionKey") + "")
                    .withName(title)
                    .withBusinessKey(instanceId)
                    // .withVariable("deptLeader",join)
                    .build());
        } else {
            processInstance = processRuntime.start(ProcessPayloadBuilder
                    .start()
                    .withProcessDefinitionKey("annualVerification")
                    .withName(title)
                    .withBusinessKey(instanceId)
                    // .withVariable("deptLeader",join)
                    .build());
        }

        Task task = null;
        task = taskService.createTaskQuery()
                .processInstanceId(processInstance.getId())
                .singleResult();
        TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(SecurityUtils.getUsername()).active();
        List<Task> todoList = query.list();//获取申请人的待办任务列表
        for (Task tmp : todoList) {
            if (tmp.getProcessInstanceId().equals(processInstance.getId())) {
                task = tmp;//获取当前流程实例，当前申请人的待办任务
                break;
            }
        }
        HashMap<String, Object> variables = new HashMap<String, Object>();
        List<Map<String, Object>> actForm = (List<Map<String, Object>>) map.get("actForm");
        for (Map<String, Object> form : actForm) {
            variables.put(String.valueOf(form.get("controlId")), form.get("controlValue"));
        }
        variables.put("toUnderwriter", 0);
        taskService.complete(task.getId(), variables);

        //h_basic_information ============================================
        List<Map<String, Object>> dealernameList = (List<Map<String, Object>>) map.get("dealername");
        Map<String, Object> groupName = (Map<String, Object>) map.get("groupName");
        if (dealernameList != null && dealernameList.size() > 0) {
            for (Map<String, Object> stringObjectMap : dealernameList) {
                String gm = (String) stringObjectMap.get("GM");
                String dealerCodeFromManufacturer = (String) stringObjectMap.get("dealerCodeFromManufacturer");
                String dealerCodeFromWFS = (String) stringObjectMap.get("dealerCodeFromWFS");
                String dealerNameCN = (String) stringObjectMap.get("dealerNameCN");
                String dealerNameEN = (String) stringObjectMap.get("dealerNameEN");
                String dealername = (String) stringObjectMap.get("dealername");
                String incorporationDate = (String) stringObjectMap.get("incorporationDate");
                String joinSectorDealerNetworkDate = (String) stringObjectMap.get("joinSectorDealerNetworkDate");
                String paidupCapital = (String) stringObjectMap.get("paidupCapital");
                String province = (String) stringObjectMap.get("province");
                Object relatedWorkingExperience = stringObjectMap.get("relatedWorkingExperience");
                Integer relatedWorkingExperienceInt = (Integer) relatedWorkingExperience;
                String value = (String) stringObjectMap.get("value");
                StringBuilder sector = new StringBuilder();
                List sectorList = (List) stringObjectMap.get("sector");//数组
                if (sectorList != null && sectorList.size() > 0) {
                    for (int i = 0; i < sectorList.size(); i++) {
                        sector.append(sectorList.get(i));
                        sector.append(",");
                    }
                }
                if (!StringUtils.isEmpty(sector)) {
                    sector.deleteCharAt(sector.length() - 1);
                    System.out.println("sector" + sector);
                }
                // StringBuilder shareholdersAndShare=new StringBuilder();
                StringBuilder shareholders = new StringBuilder();
                StringBuilder share = new StringBuilder();
                List shareholdersAndShareList = (List) stringObjectMap.get("shareholdersAndShare");//数组
                if (shareholdersAndShareList != null && shareholdersAndShareList.size() > 0) {
                    for (int i = 0; i < shareholdersAndShareList.size(); i++) {
                        Map<String, Object> stringObjectMap1 = (Map<String, Object>) shareholdersAndShareList.get(i);
                        String s1 = (String) stringObjectMap1.get("shareholders");
                        String s2 = (String) stringObjectMap1.get("share");
                        shareholders.append(s1);
                        shareholders.append(",");
                        share.append(s2);
                        share.append(",");
                    }
                }
                if (!StringUtils.isEmpty(shareholders)) {
                    shareholders.deleteCharAt(shareholders.length() - 1);
                    System.out.println("shareholders" + shareholders);
                }
                if (!StringUtils.isEmpty(share)) {
                    share.deleteCharAt(share.length() - 1);
                    System.out.println("share" + share);
                }

                BasicInformation basicInformation = new BasicInformation();
                if (groupName != null) {
                    basicInformation.setGroupNameCN((String) groupName.get("groupNameCN"));
                    basicInformation.setGroupNameEN((String) groupName.get("groupNameEN"));
                }
                basicInformation.setId(IdUtils.simpleUUID());
                if (!StringUtils.isEmpty(gm)) {
                    basicInformation.setGm(gm);
                }
                if (!StringUtils.isEmpty(dealerCodeFromManufacturer)) {
                    basicInformation.setDealerCodeFromManufacturer(dealerCodeFromManufacturer);
                }
                if (!StringUtils.isEmpty(dealerCodeFromWFS)) {
                    basicInformation.setDealerCodeFromWFS(dealerCodeFromWFS);
                }
                if (!StringUtils.isEmpty(dealerNameCN)) {
                    basicInformation.setDealerNameCN(dealerNameCN);
                }
                if (!StringUtils.isEmpty(dealerNameEN)) {
                    basicInformation.setDealerNameEN(dealerNameEN);
                }
                if (!StringUtils.isEmpty(dealername)) {
                    basicInformation.setDealername(dealername);
                }
                if (!StringUtils.isEmpty(incorporationDate)) {
                    basicInformation.setIncorporationDate(incorporationDate);
                }
                if (!StringUtils.isEmpty(joinSectorDealerNetworkDate)) {
                    basicInformation.setJoinSectorDealerNetworkDate(joinSectorDealerNetworkDate);
                }
                if (!StringUtils.isEmpty(paidupCapital)) {
                    basicInformation.setPaidupCapital(Long.parseLong(paidupCapital));
                }
                if (!StringUtils.isEmpty(province)) {
                    basicInformation.setProvince(province);
                }
                if (relatedWorkingExperienceInt != null) {
                    basicInformation.setRelatedWorkingExperience(relatedWorkingExperienceInt);
                }
                if (!StringUtils.isEmpty(sector)) {
                    basicInformation.setSector(sector.toString());
                }
                if (!StringUtils.isEmpty(shareholders)) {
                    basicInformation.setShareholders(shareholders.toString());
                }
                if (!StringUtils.isEmpty(share)) {
                    basicInformation.setShare(share.toString());
                }
                if (!StringUtils.isEmpty(value)) {
                    basicInformation.setDealerValue(value);
                }
                basicInformation.setInstanceId(instanceId);
                basicInformationMapper.insertBasicInformation(basicInformation);
            }
        }


        //TODO 没有传来
        //h_detail_information ============================================
        List<DetailInformation> detailInformationList = (List<DetailInformation>) map.get("dealer_background");
        System.out.println("detailInformationList==" + detailInformationList);
        String detailInformationLists = JSON.toJSONString(detailInformationList);
        detailInformationList = JSON.parseArray(detailInformationLists, DetailInformation.class);
        if (detailInformationList != null && detailInformationList.size() > 0) {
            for (DetailInformation detailInformation : detailInformationList) {
                detailInformation.setDealerId(detailInformation.getId());
                detailInformation.setId(IdUtils.simpleUUID());
                detailInformation.setInstanceId(instanceId);
                detailInformationMapper.insertDetailInformation(detailInformation);
            }
        }

        //————————————————————————————————————————————————————————————————————————————————————

        //TODO-已完成
        //h_sales_performance_and_target ============================================
        List<SalesPerformanceAndTargetVO> salesPerformanceAndTargetVOList = (List<SalesPerformanceAndTargetVO>) map.get("sales_performance_and_target");
        System.out.println("salesPerformanceAndTargetVOList==" + salesPerformanceAndTargetVOList);
        String salesPerformanceAndTargetVOLists = JSON.toJSONString(salesPerformanceAndTargetVOList);
        salesPerformanceAndTargetVOList = JSON.parseArray(salesPerformanceAndTargetVOLists, SalesPerformanceAndTargetVO.class);
        if (salesPerformanceAndTargetVOList != null && salesPerformanceAndTargetVOList.size() > 0) {
            for (SalesPerformanceAndTargetVO salesPerformanceAndTargetVO : salesPerformanceAndTargetVOList) {
                SalesPerformanceAndTarget salesPerformanceAndTarget = new SalesPerformanceAndTarget();
                salesPerformanceAndTarget.setId(IdUtils.simpleUUID());
                salesPerformanceAndTarget.setDealerId(salesPerformanceAndTargetVO.getId());
                salesPerformanceAndTarget.setDealername(salesPerformanceAndTargetVO.getDealername());
                salesPerformanceAndTarget.setItem(salesPerformanceAndTargetVO.getItem());
                salesPerformanceAndTarget.setSector(salesPerformanceAndTargetVO.getSector());
                salesPerformanceAndTarget.setActual2021(salesPerformanceAndTargetVO.getYR2021Actual());
                salesPerformanceAndTarget.setActualYTD2022(salesPerformanceAndTargetVO.getActualYTDyear2());
                salesPerformanceAndTarget.setTarget2022(salesPerformanceAndTargetVO.getTarget2022());
                salesPerformanceAndTarget.setIndexId(salesPerformanceAndTargetVO.getIndex());
                salesPerformanceAndTarget.setInstanceId(instanceId);
                salesPerformanceAndTargetMapper.insertSalesPerformanceAndTarget(salesPerformanceAndTarget);
            }
        }

        //TODO-已完成，------
        //h_limit_calculation_for_commerical_needs ============================================
        List<LimitCalculationForCommericalNeedVO> limitCalculationForCommericalNeeds = (List<LimitCalculationForCommericalNeedVO>) map.get("limit_calculation_for_commerical_needs");
        System.out.println("limitCalculationForCommericalNeeds==" + limitCalculationForCommericalNeeds);
        String limitCalculationForCommericalNeedss = JSON.toJSONString(limitCalculationForCommericalNeeds);
        limitCalculationForCommericalNeeds = JSON.parseArray(limitCalculationForCommericalNeedss, LimitCalculationForCommericalNeedVO.class);
        if (limitCalculationForCommericalNeeds != null && limitCalculationForCommericalNeeds.size() > 0) {
            for (LimitCalculationForCommericalNeedVO limitCalculationForCommericalNeedVO : limitCalculationForCommericalNeeds) {
                LimitCalculationForCommericalNeeds limitCalculationForCommericalNeed = new LimitCalculationForCommericalNeeds();
                BeanUtils.copyProperties(limitCalculationForCommericalNeedVO, limitCalculationForCommericalNeed);
                limitCalculationForCommericalNeed.setId(IdUtils.simpleUUID());
                limitCalculationForCommericalNeed.setDealerId(limitCalculationForCommericalNeedVO.getId());
                limitCalculationForCommericalNeed.setInstanceId(instanceId);
                limitCalculationForCommericalNeedsMapper.insertLimitCalculationForCommericalNeeds(limitCalculationForCommericalNeed);
            }
        }

        //TODO-已完成，------
        //h_other_financing_resource ============================================
        List<OtherFinancingResourceVO> otherFinancingResourceVOs = (List<OtherFinancingResourceVO>) map.get("other_financing_resource");
        System.out.println("otherFinancingResourceVOs==" + otherFinancingResourceVOs);
        String otherFinancingResourceVOss = JSON.toJSONString(otherFinancingResourceVOs);
        otherFinancingResourceVOs = JSON.parseArray(otherFinancingResourceVOss, OtherFinancingResourceVO.class);
        if (otherFinancingResourceVOs != null && otherFinancingResourceVOs.size() > 0) {
            for (OtherFinancingResourceVO otherFinancingResourceVO : otherFinancingResourceVOs) {
                OtherFinancingResource otherFinancingResource = new OtherFinancingResource();
                otherFinancingResource.setId(IdUtils.simpleUUID());
                otherFinancingResource.setDealerId(otherFinancingResourceVO.getId());
                otherFinancingResource.setDealername(otherFinancingResourceVO.getDealername());
                otherFinancingResource.setIndex(otherFinancingResourceVO.getIndex());
                otherFinancingResource.setInstitutionName(otherFinancingResourceVO.getInstitutionname());
                otherFinancingResource.setLoanType(otherFinancingResourceVO.getLoantype());
                otherFinancingResource.setApprovedLimit(otherFinancingResourceVO.getApprovedlimit());
                otherFinancingResource.setOs(otherFinancingResourceVO.getOs());
                otherFinancingResource.setSecurity(otherFinancingResourceVO.getSecurity());
                otherFinancingResource.setInterestRate(otherFinancingResourceVO.getInterestrate());
                otherFinancingResource.setDueDate(otherFinancingResourceVO.getDuedate());
                otherFinancingResource.setPurpose(otherFinancingResourceVO.getPurpose());
                otherFinancingResource.setInstanceId(instanceId);
                otherFinancingResourceMapper.insertOtherFinancingResource(otherFinancingResource);
            }
        }

        //TODO ,传来了
        //h_temporary_condition_follow_up ============================================
        // Object temporary_condition_follow_up = map.get("h_temporary_condition_follow_up");
        List<TemporaryConditionFollowUp> temporaryConditionFollowUps = (List<TemporaryConditionFollowUp>) map.get("temporary_condition_follow_up");
        System.out.println("temporaryConditionFollowUps==" + temporaryConditionFollowUps);
        String temporaryConditionFollowUpss = JSON.toJSONString(temporaryConditionFollowUps);
        temporaryConditionFollowUps = JSON.parseArray(temporaryConditionFollowUpss, TemporaryConditionFollowUp.class);
        if (temporaryConditionFollowUps != null && temporaryConditionFollowUps.size() > 0) {
            for (TemporaryConditionFollowUp temporaryConditionFollowUp : temporaryConditionFollowUps) {
                temporaryConditionFollowUp.setDealerId(temporaryConditionFollowUp.getId());
                temporaryConditionFollowUp.setId(IdUtils.simpleUUID());
                temporaryConditionFollowUp.setInstanceId(instanceId);
                temporaryConditionFollowUpMapper.insertTemporaryConditionFollowUp(temporaryConditionFollowUp);
            }
        }

        //TODO 没有传来
      /*  Object approved_limit_and_condition = map.get("approved_limit_and_condition");
        System.out.println("approved_limit_and_condition==" + approved_limit_and_condition);
        if (approved_limit_and_condition != null) {
            List<ApprovedLimitAndConditionVO> approvedLimitAndConditionVOs = (List<ApprovedLimitAndConditionVO>) approved_limit_and_condition;
            String s = JSON.toJSONString(approvedLimitAndConditionVOs);
            approvedLimitAndConditionVOs = JSON.parseArray(s, ApprovedLimitAndConditionVO.class);
            for (ApprovedLimitAndConditionVO approvedLimitAndConditionVO : approvedLimitAndConditionVOs) {
                ApprovedLimitAndCondition approvedLimitAndCondition = new ApprovedLimitAndCondition();
                BeanUtils.copyProperties(approvedLimitAndConditionVO, approvedLimitAndCondition);
                approvedLimitAndCondition.setId(IdUtils.simpleUUID());
                approvedLimitAndCondition.setDealerid(IdUtils.simpleUUID());
                approvedLimitAndCondition.setInstanceid(instanceId);

                DetailInformation detailInformation = new DetailInformation();
                detailInformation.setId(IdUtils.simpleUUID());
                detailInformation.setDealerId(IdUtils.simpleUUID());
                detailInformation.setDealername(approvedLimitAndConditionVO.getDealername());
                detailInformation.setMonth(approvedLimitAndConditionVO.getMonth());
                detailInformation.setLoyaltyGrade(approvedLimitAndConditionVO.getLoyaltyGrade());

                approvedLimitAndConditionMapper.insertApprovedLimitAndCondition(approvedLimitAndCondition);
                detailInformationMapper.insertDetailInformation(detailInformation);
            }
        }*/

        //h_proposal_by_commerical_and_marketing ============================================
        // Object proposal_by_commerical_and_marketing = map.get("proposal_by_commerical_and_marketing_evaluate");
        Object proposal_by_commerical_and_marketing = map.get("proposal_by_commerical_and_marketing");
        if (proposal_by_commerical_and_marketing != null) {
            List<ProposalByCommericalAndMarketingVO> proposalByCommericalAndMarketings = (List<ProposalByCommericalAndMarketingVO>) proposal_by_commerical_and_marketing;
            String s = JSON.toJSONString(proposalByCommericalAndMarketings);
            proposalByCommericalAndMarketings = JSON.parseArray(s, ProposalByCommericalAndMarketingVO.class);
            for (ProposalByCommericalAndMarketingVO proposalByCommericalAndMarketingVO : proposalByCommericalAndMarketings) {
                ProposalByCommericalAndMarketing proposalByCommericalAndMarketing = new ProposalByCommericalAndMarketing();
                BeanUtils.copyProperties(proposalByCommericalAndMarketingVO, proposalByCommericalAndMarketing);
                proposalByCommericalAndMarketing.setId(IdUtils.simpleUUID());
                proposalByCommericalAndMarketing.setDealerId(proposalByCommericalAndMarketingVO.getId());
                proposalByCommericalAndMarketing.setInstanceId(instanceId);
                proposalByCommericalAndMarketingMapper.insertProposalByCommericalAndMarketing(proposalByCommericalAndMarketing);
            }
        }

        //TODO 没有传来
        //h_wholesale_performance_currently ============================================
        String wholesale_performance_currently = (String) map.get("wholesale_performance_currently");
        if (!StringUtils.isEmpty(wholesale_performance_currently)) {
            List<WholesalePerformanceCurrently> wholesalePerformanceCurrentlies = JSON.parseArray(wholesale_performance_currently, WholesalePerformanceCurrently.class);
            for (WholesalePerformanceCurrently wholesalePerformanceCurrently : wholesalePerformanceCurrentlies) {
                wholesalePerformanceCurrently.setId(IdUtils.simpleUUID());
                wholesalePerformanceCurrently.setDealerId(IdUtils.simpleUUID());
                wholesalePerformanceCurrently.setInstanceId(instanceId);
                wholesalePerformanceCurrentlyMapper.insertWholesalePerformanceCurrently(wholesalePerformanceCurrently);
            }
        }

        //TODO 没有传来
        //h_wholesale_performance_recent_three_months ============================================
        String wholesale_performance_recent_three_months = (String) map.get("wholesale_performance_recent_three_months");
        if (!StringUtils.isEmpty(wholesale_performance_recent_three_months)) {
            List<WholesalePerformanceRecentThreeMonths> wholesalePerformanceRecentThreeMonths = JSON.parseArray(wholesale_performance_recent_three_months, WholesalePerformanceRecentThreeMonths.class);
            for (WholesalePerformanceRecentThreeMonths wholesalePerformanceRecentThreeMonth : wholesalePerformanceRecentThreeMonths) {
                wholesalePerformanceRecentThreeMonth.setId(IdUtils.simpleUUID());
                wholesalePerformanceRecentThreeMonth.setDealerId(IdUtils.simpleUUID());
                wholesalePerformanceRecentThreeMonth.setInstanceId(instanceId);
                wholesalePerformanceRecentThreeMonthsMapper.insertWholesalePerformanceRecentThreeMonths(wholesalePerformanceRecentThreeMonth);
            }
        }

        //h_securities ============================================
        List<SecuritieVO> securitiesList = (List<SecuritieVO>) map.get("securities");
        System.out.println("securitiesList==" + securitiesList);
        String securitiesLists = JSON.toJSONString(securitiesList);
        securitiesList = JSON.parseArray(securitiesLists, SecuritieVO.class);
        if (securitiesList != null && securitiesList.size() > 0) {
            for (SecuritieVO securitieVO : securitiesList) {
                Securities securitie = new Securities();
                BeanUtils.copyProperties(securitieVO, securitie);
                securitie.setId(IdUtils.simpleUUID());
                securitie.setDealerId(securitieVO.getId());
                securitie.setInstanceId(instanceId);
                securitiesMapper.insertSecurities(securitie);
            }
        }

        //h_notes ============================================
        Notes notes = new Notes();
        //String notesId = UUID.randomUUID().toString().replace("-", "");
        notes.setId(IdUtils.simpleUUID());
        notes.setInstanceId(instanceId);
        notes.setBasicNotes((String) map.get("basicNotes"));
        notes.setDealerNotes((String) map.get("dealerNotes"));
        notes.setLoyaltyNotes((String) map.get("loyaltyNotes"));
        notes.setAuditNotes((String) map.get("auditNotes"));
        notes.setWholesaleNotes((String) map.get("wholesaleNotes"));
        notes.setProposalNotes((String) map.get("proposalNotes"));
        notesMapper.insertNotes(notes);

        List<Map> applications = (List<Map>) map.get("application");
        System.out.println("applications==" + applications);
        if (applications != null && applications.size() > 0) {
            for (Map fileuploadVO : applications) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(fileuploadVO.get("fileName").toString());
                fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                fileupload.setUrl(fileuploadVO.get("url").toString());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("application");
                fileuploadService.insertFileupload(fileupload);
            }
        }

        List<Map> informations = (List<Map>) map.get("information");
        System.out.println("informations==" + informations);
        if (informations != null && informations.size() > 0) {
            for (Map fileuploadVO : informations) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(fileuploadVO.get("fileName").toString());
                fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                fileupload.setUrl(fileuploadVO.get("url").toString());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("information");
                fileuploadService.insertFileupload(fileupload);
            }
        }

        List<Map> financialss = (List<Map>) map.get("financials");
        System.out.println("financialss==" + financialss);
        if (financialss != null && financialss.size() > 0) {
            for (Map fileuploadVO : financialss) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(fileuploadVO.get("fileName").toString());
                fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                fileupload.setUrl(fileuploadVO.get("url").toString());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("financials");
                fileuploadService.insertFileupload(fileupload);
            }
        }

        List<Map> guarantees = (List<Map>) map.get("guarantee");
        System.out.println("guarantees==" + guarantees);
        if (guarantees != null && guarantees.size() > 0) {
            for (Map fileuploadVO : guarantees) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(fileuploadVO.get("fileName").toString());
                fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                fileupload.setUrl(fileuploadVO.get("url").toString());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("guarantee");
                fileuploadService.insertFileupload(fileupload);
            }
        }

        List<Map> corporates = (List<Map>) map.get("corporate");
        System.out.println("corporates==" + corporates);
        if (corporates != null && corporates.size() > 0) {
            for (Map fileuploadVO : corporates) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(fileuploadVO.get("fileName").toString());
                fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                fileupload.setUrl(fileuploadVO.get("url").toString());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("corporate");
                fileuploadService.insertFileupload(fileupload);
            }
        }

        List<Map> others = (List<Map>) map.get("other");
        System.out.println("others==" + others);
        if (others != null && others.size() > 0) {
            for (Map fileuploadVO : others) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(fileuploadVO.get("fileName").toString());
                fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                fileupload.setUrl(fileuploadVO.get("url").toString());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("other");
                fileuploadService.insertFileupload(fileupload);
            }
        }

        Object opDocument = map.get("opDocument");
        if (opDocument != null) {
            List<Map> opDocuments = (List<Map>) opDocument;
            for (Map fileuploadVO : opDocuments) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(fileuploadVO.get("fileName").toString());
                fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                fileupload.setUrl(fileuploadVO.get("url").toString());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("opDocument");
                fileuploadService.insertFileupload(fileupload);
            }
        }


        AnnualReviewy annualReviewy = new AnnualReviewy();
        annualReviewy.setId(IdUtils.simpleUUID());
        annualReviewy.setTitle(title);
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setInstanceId(instanceId);
        annualReviewy.setState("0");
        if (StringUtils.isNotNull(map.get("processDefinitionKey"))) {
            annualReviewy.setType(map.get("processDefinitionKey") + "");
        } else {
            annualReviewy.setType("annualVerification");
        }

        annualReviewy.setCreateName(SecurityUtils.getNickName());
        annualReviewy.setCreateBy(SecurityUtils.getUsername());
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        return annualReviewyMapper.insertAnnualReviewy(annualReviewy);
    }

    public int updateAnnualReviewyByInstanceId(AnnualReviewy annualReviewy) {
        return annualReviewyMapper.updateAnnualReviewyByInstanceId(annualReviewy);
    }

    public int closeUpdateAnnualReviewyObj(String instanceId, String username) {
        return annualReviewyMapper.closeUpdateAnnualReviewyObj(instanceId, username);
    }

    public int openUpdateAnnualReviewyObj(String username) {
        return annualReviewyMapper.openUpdateAnnualReviewyObj(username);
    }

    @Override
    public List getInfoListByDealerName(String dealerName) {
        List list = dealerInformationMapper.getInfoListByDealerName(dealerName);
        return list;
    }

    /**
     * 修改feike
     *
     * @param map feike
     * @return 结果
     */
    @Override
    @Transactional
    public int updateAnnualReviewy(Map<String, Object> map) {
        String instanceId = (String) map.get("instanceId");

        Map<String, Object> basic_informations = (Map<String, Object>) map.get("groupName");
        // if (basic_informations != null) {
        //     BasicInformation basicInformation = basicInformationMapper.selectDealerGroupByByInstanceId(instanceId);
        //     basicInformation.setGroupNameCN((String) basic_informations.get("groupNameCN"));
        //     basicInformation.setGroupNameEN((String) basic_informations.get("groupNameEN"));
        //     basicInformationMapper.updateBasicInformation(basicInformation);
        // }

        //TODO 没有传来
        //h_detail_information ============================================
        Object dealer_background = map.get("dealer_background");
        if (dealer_background != null) {
            List<DetailInformation> detailInformationList = (List<DetailInformation>) dealer_background;
            String s = JSON.toJSONString(detailInformationList);
            detailInformationList = JSON.parseArray(s, DetailInformation.class);
            for (DetailInformation detailInformation : detailInformationList) {
                // detailInformation.setDealerId(detailInformation.getId());
                // detailInformation.setId(IdUtils.simpleUUID());
                // detailInformation.setInstanceId(instanceId);
                detailInformationMapper.insertDetailInformation(detailInformation);
            }
        }

        //————————————————————————————————————————————————————————————————————————————————————

        //TODO-已完成
        //h_sales_performance_and_target ============================================
        Object sales_performance_and_targets = map.get("sales_performance_and_target");
        if (sales_performance_and_targets != null) {
            List<SalesPerformanceAndTargetVO> SalesPerformanceAndTargetVOList = new ArrayList<>();
            SalesPerformanceAndTargetVOList = (List<SalesPerformanceAndTargetVO>) sales_performance_and_targets;
            String s = JSON.toJSONString(SalesPerformanceAndTargetVOList);
            SalesPerformanceAndTargetVOList = JSON.parseArray(s, SalesPerformanceAndTargetVO.class);

            for (SalesPerformanceAndTargetVO salesPerformanceAndTargetVO : SalesPerformanceAndTargetVOList) {
                SalesPerformanceAndTarget salesPerformanceAndTarget = salesPerformanceAndTargetMapper.selectSalesPerformanceAndTargetById(salesPerformanceAndTargetVO.getId());
                salesPerformanceAndTarget.setDealername(salesPerformanceAndTargetVO.getDealername());
                salesPerformanceAndTarget.setItem(salesPerformanceAndTargetVO.getItem());
                salesPerformanceAndTarget.setSector(salesPerformanceAndTargetVO.getSector());
                salesPerformanceAndTarget.setActual2021(salesPerformanceAndTargetVO.getYR2021Actual());
                salesPerformanceAndTarget.setActualYTD2022(salesPerformanceAndTargetVO.getActualYTDyear2());
                salesPerformanceAndTarget.setTarget2022(salesPerformanceAndTargetVO.getTarget2022());
                salesPerformanceAndTarget.setIndexId(salesPerformanceAndTargetVO.getIndex());
                salesPerformanceAndTargetMapper.updateSalesPerformanceAndTarget(salesPerformanceAndTarget);
            }
        }

        //TODO-已完成，------
        //h_limit_calculation_for_commerical_needs ============================================
        Object limit_calculation_for_commerical_needs = map.get("limit_calculation_for_commerical_needs");
        if (limit_calculation_for_commerical_needs != null) {
            List<LimitCalculationForCommericalNeedVO> limitCalculationForCommericalNeeds = new ArrayList<>();
            limitCalculationForCommericalNeeds = (List<LimitCalculationForCommericalNeedVO>) limit_calculation_for_commerical_needs;
            String s = JSON.toJSONString(limitCalculationForCommericalNeeds);
            limitCalculationForCommericalNeeds = JSON.parseArray(s, LimitCalculationForCommericalNeedVO.class);
            for (LimitCalculationForCommericalNeedVO limitCalculationForCommericalNeedVO : limitCalculationForCommericalNeeds) {
                LimitCalculationForCommericalNeeds limitCalculationForCommericalNeed = limitCalculationForCommericalNeedsMapper.selectLimitCalculationForCommericalNeedsById(limitCalculationForCommericalNeedVO.getId());
                BeanUtils.copyProperties(limitCalculationForCommericalNeedVO, limitCalculationForCommericalNeed);
                limitCalculationForCommericalNeedsMapper.updateLimitCalculationForCommericalNeeds(limitCalculationForCommericalNeed);
            }
        }

        //TODO-已完成，------
        //h_other_financing_resource ============================================
        Object other_financing_resource = map.get("other_financing_resource");
        if (other_financing_resource != null) {
            List<OtherFinancingResourceVO> otherFinancingResourceVOs = new ArrayList<>();
            otherFinancingResourceVOs = (List<OtherFinancingResourceVO>) other_financing_resource;
            String s = JSON.toJSONString(otherFinancingResourceVOs);
            otherFinancingResourceVOs = JSON.parseArray(s, OtherFinancingResourceVO.class);
            for (OtherFinancingResourceVO otherFinancingResourceVO : otherFinancingResourceVOs) {
                OtherFinancingResource otherFinancingResource = otherFinancingResourceMapper.selectOtherFinancingResourceById(otherFinancingResourceVO.getId());
                otherFinancingResource.setDealerId(otherFinancingResourceVO.getId());
                otherFinancingResource.setDealername(otherFinancingResourceVO.getDealername());
                otherFinancingResource.setIndex(otherFinancingResourceVO.getIndex());
                otherFinancingResource.setInstitutionName(otherFinancingResourceVO.getInstitutionname());
                otherFinancingResource.setLoanType(otherFinancingResourceVO.getLoantype());
                otherFinancingResource.setApprovedLimit(otherFinancingResourceVO.getApprovedlimit());
                otherFinancingResource.setOs(otherFinancingResourceVO.getOs());
                otherFinancingResource.setSecurity(otherFinancingResourceVO.getSecurity());
                otherFinancingResource.setInterestRate(otherFinancingResourceVO.getInterestrate());
                otherFinancingResource.setDueDate(otherFinancingResourceVO.getDuedate());
                otherFinancingResource.setPurpose(otherFinancingResourceVO.getPurpose());
                otherFinancingResourceMapper.updateOtherFinancingResource(otherFinancingResource);
            }
        }

        //TODO 没有传来
        //temporary_condition_follow_up ============================================
        Object temporary_condition_follow_up = map.get("temporary_condition_follow_up");
        if (temporary_condition_follow_up != null) {
            List<TemporaryConditionFollowUpVo> temporaryConditionFollowUpVos = new ArrayList<>();
            temporaryConditionFollowUpVos = (List<TemporaryConditionFollowUpVo>) temporary_condition_follow_up;
            String s = JSON.toJSONString(temporaryConditionFollowUpVos);
            temporaryConditionFollowUpVos = JSON.parseArray(s, TemporaryConditionFollowUpVo.class);
            for (TemporaryConditionFollowUpVo temporaryConditionFollowUpVo : temporaryConditionFollowUpVos) {
                if (null != temporaryConditionFollowUpVo.getId()) {
                    TemporaryConditionFollowUp temporaryConditionFollowUp = temporaryConditionFollowUpMapper.selectTemporaryConditionFollowUpById(temporaryConditionFollowUpVo.getId());
                    temporaryConditionFollowUp.setDealername(temporaryConditionFollowUpVo.getDealername());
                    temporaryConditionFollowUp.setConditionDate(temporaryConditionFollowUpVo.getConditionDate());
                    temporaryConditionFollowUp.setCondition(temporaryConditionFollowUpVo.getCondition());
                    temporaryConditionFollowUp.setDueDate(temporaryConditionFollowUpVo.getDueDate());
                    String tmp = "";
                    for (int i = 0; i < temporaryConditionFollowUpVo.getRole().size(); i++) {
                        if (i < temporaryConditionFollowUpVo.getRole().size() - 1) {
                            tmp += temporaryConditionFollowUpVo.getRole().get(i) + ",";
                        } else {
                            tmp += temporaryConditionFollowUpVo.getRole().get(i);
                        }
                    }
                    temporaryConditionFollowUp.setRole(tmp);
                    temporaryConditionFollowUp.setComments(temporaryConditionFollowUpVo.getComments());
                    temporaryConditionFollowUp.setCurrentStatus(temporaryConditionFollowUpVo.getCurrentStatus());
                    temporaryConditionFollowUpMapper.updateTemporaryConditionFollowUp(temporaryConditionFollowUp);
                } else {
                    TemporaryConditionFollowUp temporaryConditionFollowUp = new TemporaryConditionFollowUp();
                    temporaryConditionFollowUp.setId(IdUtils.simpleUUID());
                    temporaryConditionFollowUp.setDealername(temporaryConditionFollowUpVo.getDealername());
                    temporaryConditionFollowUp.setConditionDate(temporaryConditionFollowUpVo.getConditionDate());
                    temporaryConditionFollowUp.setCondition(temporaryConditionFollowUpVo.getCondition());
                    temporaryConditionFollowUp.setDueDate(temporaryConditionFollowUpVo.getDueDate());
                    String tmp = "";
                    for (int i = 0; i < temporaryConditionFollowUpVo.getRole().size(); i++) {
                        if (i < temporaryConditionFollowUpVo.getRole().size() - 1) {
                            tmp += temporaryConditionFollowUpVo.getRole().get(i) + ",";
                        } else {
                            tmp += temporaryConditionFollowUpVo.getRole().get(i);
                        }
                    }
                    temporaryConditionFollowUp.setRole(tmp);
                    temporaryConditionFollowUp.setComments(temporaryConditionFollowUpVo.getComments());
                    temporaryConditionFollowUp.setCurrentStatus(temporaryConditionFollowUpVo.getCurrentStatus());
                    temporaryConditionFollowUp.setIsExist(temporaryConditionFollowUpVo.getIsExist());
                    temporaryConditionFollowUp.setInstanceId(instanceId);
                    temporaryConditionFollowUpMapper.insertTemporaryConditionFollowUp(temporaryConditionFollowUp);
                }
            }
        }

        //TODO 没有传来
        //h_proposal_by_commerical_and_marketing ============================================
        Object proposal_by_commerical_and_marketing = map.get("proposal_by_commerical_and_marketing");
        if (proposal_by_commerical_and_marketing != null) {
            List<ProposalByCommericalAndMarketingVO> proposalByCommericalAndMarketings = new ArrayList<>();
            proposalByCommericalAndMarketings = (List<ProposalByCommericalAndMarketingVO>) proposal_by_commerical_and_marketing;
            String s = JSON.toJSONString(proposalByCommericalAndMarketings);
            proposalByCommericalAndMarketings = JSON.parseArray(s, ProposalByCommericalAndMarketingVO.class);
            for (ProposalByCommericalAndMarketingVO proposalByCommericalAndMarketingVO : proposalByCommericalAndMarketings) {
                ProposalByCommericalAndMarketing proposalByCommericalAndMarketing = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingById(proposalByCommericalAndMarketingVO.getId());
                BeanUtils.copyProperties(proposalByCommericalAndMarketingVO, proposalByCommericalAndMarketing);
                proposalByCommericalAndMarketingMapper.updateProposalByCommericalAndMarketing(proposalByCommericalAndMarketing);
            }
        }

        //TODO 没有传来
        //h_wholesale_performance_currently ============================================
        String wholesale_performance_currently = (String) map.get("wholesale_performance_currently");
        if (!StringUtils.isEmpty(wholesale_performance_currently)) {
            List<WholesalePerformanceCurrently> wholesalePerformanceCurrentlies = JSON.parseArray(wholesale_performance_currently, WholesalePerformanceCurrently.class);
            for (WholesalePerformanceCurrently wholesalePerformanceCurrently : wholesalePerformanceCurrentlies) {
                wholesalePerformanceCurrently.setInstanceId(instanceId);
                wholesalePerformanceCurrentlyMapper.updateWholesalePerformanceCurrently(wholesalePerformanceCurrently);
            }
        }

        //TODO 没有传来
        //h_wholesale_performance_recent_three_months ============================================
        String wholesale_performance_recent_three_months = (String) map.get("wholesale_performance_recent_three_months");
        if (!StringUtils.isEmpty(wholesale_performance_recent_three_months)) {
            List<WholesalePerformanceRecentThreeMonths> wholesalePerformanceRecentThreeMonths = JSON.parseArray(wholesale_performance_recent_three_months, WholesalePerformanceRecentThreeMonths.class);
            for (WholesalePerformanceRecentThreeMonths wholesalePerformanceRecentThreeMonth : wholesalePerformanceRecentThreeMonths) {
                wholesalePerformanceRecentThreeMonth.setInstanceId(instanceId);
                wholesalePerformanceRecentThreeMonthsMapper.updateWholesalePerformanceRecentThreeMonths(wholesalePerformanceRecentThreeMonth);
            }
        }

        //h_securities ============================================
        Object securities = map.get("securities");
        if (securities != null) {
            List<SecuritieVO> securitiesList = new ArrayList<>();
            securitiesList = (List<SecuritieVO>) securities;
            String s = JSON.toJSONString(securitiesList);
            securitiesList = JSON.parseArray(s, SecuritieVO.class);
            for (SecuritieVO securitieVO : securitiesList) {
                Securities securitie = securitiesMapper.selectSecuritiesById(securitieVO.getId());
                BeanUtils.copyProperties(securitieVO, securitie);
                securitiesMapper.updateSecurities(securitie);
            }
        }

        //h_notes ============================================
        Notes notes = notesMapper.selectNotesByInstanceId(instanceId);
        if(notes!=null){
            notes.setBasicNotes((String) map.get("basicNotes"));
            notes.setDealerNotes((String) map.get("dealerNotes"));
            notes.setLoyaltyNotes((String) map.get("loyaltyNotes"));
            notes.setAuditNotes((String) map.get("auditNotes"));
            notes.setWholesaleNotes((String) map.get("wholesaleNotes"));
            notes.setProposalNotes((String) map.get("proposalNotes"));
            notesMapper.updateNotes(notes);
        }

        Object application = map.get("application");
        if (application != null) {
            List<Map> applications = (List<Map>) application;
            for (Map fileuploadVO : applications) {
                if (null == fileuploadVO.get("id")) {
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("application");
                    fileuploadService.insertFileupload(fileupload);
                }
            }
        }

        Object information = map.get("information");
        if (information != null) {
            List<Map> informations = (List<Map>) information;
            for (Map fileuploadVO : informations) {
                if (null == fileuploadVO.get("id")) {
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("information");
                    fileuploadService.insertFileupload(fileupload);
                }
            }
        }

        Object financials = map.get("financials");
        if (financials != null) {
            List<Map> financialss = (List<Map>) financials;
            for (Map fileuploadVO : financialss) {
                if (null == fileuploadVO.get("id")) {
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("financials");
                    fileuploadService.insertFileupload(fileupload);
                }
            }
        }

        Object guarantee = map.get("guarantee");
        if (guarantee != null) {
            List<Map> guarantees = (List<Map>) guarantee;
            for (Map fileuploadVO : guarantees) {
                if (null == fileuploadVO.get("id")) {
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("guarantee");
                    fileuploadService.insertFileupload(fileupload);
                }
            }
        }

        Object corporate = map.get("corporate");
        if (corporate != null) {
            List<Map> corporates = (List<Map>) corporate;
            for (Map fileuploadVO : corporates) {
                if (null == fileuploadVO.get("id")) {
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("corporate");
                    fileuploadService.insertFileupload(fileupload);
                }
            }
        }

        Object other = map.get("other");
        if (other != null) {
            List<Map> others = (List<Map>) other;
            for (Map fileuploadVO : others) {
                if (null == fileuploadVO.get("id")) {
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("other");
                    fileuploadService.insertFileupload(fileupload);
                }
            }
        }

        Object financialAnalysis = map.get("financialAnalysis");
        if (financialAnalysis != null) {
            List<Map> financialAnalysiss = (List<Map>) financialAnalysis;
            for (Map fileuploadVO : financialAnalysiss) {
                if (null == fileuploadVO.get("id")) {
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("financialAnalysis");
                    fileuploadService.insertFileupload(fileupload);
                }
            }
        }

        Object pboc = map.get("pboc");
        if (pboc != null) {
            List<Map> pbocs = (List<Map>) pboc;
            for (Map fileuploadVO : pbocs) {
                if (null == fileuploadVO.get("id")) {
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("pboc");
                    fileuploadService.insertFileupload(fileupload);
                }
            }
        }

        Object lawsuit = map.get("lawsuit");
        if (lawsuit != null) {
            List<Map> lawsuits = (List<Map>) lawsuit;
            for (Map fileuploadVO : lawsuits) {
                if (null == fileuploadVO.get("id")) {
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("lawsuit");
                    fileuploadService.insertFileupload(fileupload);
                }
            }
        }

        Object opDocument = map.get("opDocument");
        if (opDocument != null) {
            List<Map> opDocuments = (List<Map>) opDocument;
            for (Map fileuploadVO : opDocuments) {
                if (null == fileuploadVO.get("id")) {
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("opDocument");
                    fileuploadService.insertFileupload(fileupload);
                }
            }
        }

        Object underwriterOther = map.get("underwriterOther");
        if (underwriterOther != null) {
            List<Map> underwriterOthers = (List<Map>) underwriterOther;
            for (Map fileuploadVO : underwriterOthers) {
                if (null == fileuploadVO.get("id")) {
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("underwriterOther");
                    fileuploadService.insertFileupload(fileupload);
                }
            }
        }

        AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId(instanceId);
        annualReviewy.setUpdateBy(SecurityUtils.getUsername());
        annualReviewy.setUpdateTime(DateUtils.getNowDate());
        annualReviewy.setUsername(null);
        return annualReviewyMapper.updateAnnualReviewy(annualReviewy);
    }

    /**
     * 批量删除feike
     *
     * @param ids 需要删除的feikeID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAnnualReviewyByIds(String[] ids) {
        List<AnnualReviewy> annualReviewyList = annualReviewyMapper.selectAnnualReviewyByIds(ids);

        if (annualReviewyList != null && annualReviewyList.size() > 0) {
            for (AnnualReviewy annualReviewy : annualReviewyList) {
                int basicInformation = basicInformationMapper.deleteBasicInformationByInstanceId(annualReviewy.getInstanceId());
                int detailInformatio = detailInformationMapper.deleteDetailInformationByInstanceId(annualReviewy.getInstanceId());
                int sales = salesPerformanceAndTargetMapper.deleteSalesPerformanceAndTargetByInstanceId(annualReviewy.getInstanceId());
                int limit = limitCalculationForCommericalNeedsMapper.deleteLimitCalculationForCommericalNeedsByInstanceId(annualReviewy.getInstanceId());
                int other = otherFinancingResourceMapper.deleteOtherFinancingResourceByInstanceId(annualReviewy.getInstanceId());
                int temporary = temporaryConditionFollowUpMapper.deleteTemporaryConditionFollowUpByInstanceId(annualReviewy.getInstanceId());
                int proposal = proposalByCommericalAndMarketingMapper.deleteProposalByCommericalAndMarketingByInstanceId(annualReviewy.getInstanceId());
                int wholesale = wholesalePerformanceCurrentlyMapper.deleteWholesalePerformanceCurrentlyByInstanceId(annualReviewy.getInstanceId());
                int wholesale111 = wholesalePerformanceRecentThreeMonthsMapper.deleteWholesalePerformanceRecentThreeMonthsByInstanceId(annualReviewy.getInstanceId());
                int securities = securitiesMapper.deleteSecuritiesByInstanceId(annualReviewy.getInstanceId());
            }
        }
        return annualReviewyMapper.deleteAnnualReviewyByIds(ids);
        // return 1;
    }

    /**
     * 删除feike信息
     *
     * @param id feikeID
     * @return 结果
     */
    @Override
    public int deleteAnnualReviewyById(String id) {
        return annualReviewyMapper.deleteAnnualReviewyById(id);
    }

    /**
     * 查询 列表带任务状态
     *
     * @param annualReviewy
     * @return
     */
    @Override
    public List<AnnualReviewy> selectAnnualReviewyAndTaskNameList(AnnualReviewy annualReviewy) {
        List<AnnualReviewy> annualReviewies = annualReviewyMapper.selectAnnualReviewyList(annualReviewy);
        List<String> collect = annualReviewies.parallelStream()
                .map(wl -> wl.getInstanceId())
                .collect(Collectors.toList());
        if (collect != null && !collect.isEmpty()) {
            List<Task> tasks = taskService.createTaskQuery()
                    .processInstanceIdIn(collect)
                    .list();
            annualReviewies.forEach(
                    wl -> {
                        Task task = tasks.parallelStream()
                                .filter(t -> t.getProcessInstanceId()
                                        .equals(wl.getInstanceId()))
                                .findAny()
                                .orElse(null);
                        if (task != null) {
                            wl.setTaskName(task.getName());
                        }
                    }
            );
        }
        return annualReviewies;
    }

    @Override
    public int startDM(Map<String, Object> map) {
        String parentId = map.get("parentId")
                .toString();
        org.activiti.engine.runtime.ProcessInstance parentInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceBusinessKey(parentId)
                .singleResult();
        String id = IdUtils.simpleUUID();
        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("startDM")
                .withName(parentInstance.getName() + "-的子流程")
                .withBusinessKey(id)
                .withVariable("parentId", parentId)
                .build());
        DealerNegativeInformationCheck dealerNegativeInformationCheck = dealerNegativeInformationCheckService.selectDealerNegativeInformationCheckById(parentId);
        DealerNegativeInformationCheck dealerNegativeInformationCheck1 = new DealerNegativeInformationCheck();
        dealerNegativeInformationCheck1.setId(parentId);
        dealerNegativeInformationCheck1.setInstanceId(parentId);
        dealerNegativeInformationCheck1.setIsStartDM(true);
        if (null == dealerNegativeInformationCheck) {
            dealerNegativeInformationCheckService.insertDealerNegativeInformationCheck(dealerNegativeInformationCheck1);
        }
        return 1;
    }

    @Override
    public int startPLM(Map<String, Object> map) {
        String parentId = map.get("parentId")
                .toString();
        org.activiti.engine.runtime.ProcessInstance parentInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceBusinessKey(parentId)
                .singleResult();
        String id = IdUtils.simpleUUID();
        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("startPLM")
                .withName(parentInstance.getName() + "-的子流程")
                .withBusinessKey(id)
                .withVariable("parentId", parentId)
                .build());
        DealerNegativeInformationCheck dealerNegativeInformationCheck = dealerNegativeInformationCheckService.selectDealerNegativeInformationCheckById(parentId);
        DealerNegativeInformationCheck dealerNegativeInformationCheck1 = new DealerNegativeInformationCheck();
        dealerNegativeInformationCheck1.setId(parentId);
        dealerNegativeInformationCheck1.setInstanceId(parentId);
        dealerNegativeInformationCheck1.setIsStartPLM(true);
        if (null == dealerNegativeInformationCheck) {
            dealerNegativeInformationCheckService.insertDealerNegativeInformationCheck(dealerNegativeInformationCheck1);
        }
        return 1;
    }

    @Override
    public int dmSelect(Map<String, Object> map) {

        return 0;
    }

    @Override
    public Map<String, Object> selectAnnualReviewyByInstanceId(String instanceId) {
        Map<String, Object> map = new HashMap<>();  //一级
        AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId(instanceId);
        if (annualReviewy != null) {
            map.put("id", annualReviewy.getId()); // id
            map.put("instanceId", annualReviewy.getInstanceId()); // instanceId
            map.put("title", annualReviewy.getTitle()); // 标题
            map.put("createTime", annualReviewy.getCreateTime()); // 创建时间
            map.put("createName", annualReviewy.getCreateName()); // 发起人中午名称
            map.put("createBy", annualReviewy.getCreateBy()); // 发起人用户名称
            map.put("username", annualReviewy.getUsername()); // 任务拾取人
        }
        Map<String, Object> data = new HashMap<>();  // 二级
        List<Map<String, Object>> childrenList = new ArrayList();

        Map<String, Object> groupName = new HashMap<>();
        List<BasicInformation> basicInformationList = basicInformationMapper.selectDealerGroupByByInstanceId(instanceId);
        if (basicInformationList != null && basicInformationList.size() > 0) {
            for (BasicInformation basicInformation : basicInformationList) {
                Map<String, Object> children = new HashMap<>();

                groupName.put("groupNameEN", basicInformation.getGroupNameEN()); // groupNameEN
                groupName.put("groupNameCN", basicInformation.getGroupNameCN()); // groupNameCN

                children.put("basicInformationId", basicInformation.getId());
                children.put("instanceId", basicInformation.getInstanceId());
                children.put("GM", basicInformation.getGm());
                children.put("dealerCodeFromManufacturer", basicInformation.getDealerCodeFromManufacturer());
                children.put("dealerCodeFromWFS", basicInformation.getDealerCodeFromWFS());
                children.put("dealerNameCN", basicInformation.getDealerNameCN());
                children.put("dealerNameEN", basicInformation.getDealerNameEN());
                children.put("dealername", basicInformation.getDealername());
                children.put("incorporationDate", basicInformation.getIncorporationDate());
                children.put("joinSectorDealerNetworkDate", basicInformation.getJoinSectorDealerNetworkDate());
                children.put("paidupCapital", basicInformation.getPaidupCapital());
                children.put("province", basicInformation.getProvince());
                children.put("relatedWorkingExperience", basicInformation.getRelatedWorkingExperience());
                children.put("value", basicInformation.getDealerValue());
                if (null != basicInformation.getSector()) {
                    String[] split = basicInformation.getSector().split(",");
                    children.put("sector", split);
                }
                ArrayList<Map<String, Object>> shareholdersAndShare = new ArrayList<>();
                if (null != basicInformation.getShareholders()) {
                    String[] shareholderStr = basicInformation.getShareholders().split(",");
                    String[] shareStr = basicInformation.getShare().split(",");
                    for (int i = 0; i < shareholderStr.length; i++) {
                        Map<String, Object> tmpObj = new HashMap<String, Object>();
                        tmpObj.put("share", shareStr[i]);
                        tmpObj.put("shareholders", shareholderStr[i]);
                        shareholdersAndShare.add(tmpObj);
                    }
                    children.put("shareholdersAndShare", shareholdersAndShare);
                }
                childrenList.add(children);
            }
        }
        data.put("groupName", groupName); // groupNameEN

        List<SalesPerformanceAndTargetVO> salesPerformanceAndTargetVOS = new ArrayList<>();
        List<SalesPerformanceAndTarget> salesPerformanceAndTargetList = salesPerformanceAndTargetMapper.selectSalesPerformanceAndTargetByInstanceId(instanceId);
        if (salesPerformanceAndTargetList != null && salesPerformanceAndTargetList.size() > 0) {
            data.put("sales_performance_and_target", salesPerformanceAndTargetList);
        }

        List<LimitCalculationForCommericalNeedVO> limitCalculationForCommericalNeedVOS = new ArrayList<>();
        List<LimitCalculationForCommericalNeeds> limitCalculationForCommericalNeedList = limitCalculationForCommericalNeedsMapper.selectLimitCalculationForCommericalNeedsByInstanceId(instanceId);
        if (limitCalculationForCommericalNeedList != null && limitCalculationForCommericalNeedList.size() > 0) {
            data.put("limit_calculation_for_commerical_needs", limitCalculationForCommericalNeedList);
        }

        List<OtherFinancingResourceVO> otherFinancingResourceVOS = new ArrayList<>();
        List<OtherFinancingResource> otherFinancingResourceList = otherFinancingResourceMapper.selectOtherFinancingResourceByInstanceId(instanceId);
        if (otherFinancingResourceList != null && otherFinancingResourceList.size() > 0) {
            data.put("other_financing_resource", otherFinancingResourceList);
        }

        List<TemporaryConditionFollowUp> temporaryConditionFollowUpList = temporaryConditionFollowUpMapper.selectTemporaryConditionFollowUpByInstanceId(instanceId);
        if (temporaryConditionFollowUpList != null && temporaryConditionFollowUpList.size() > 0) {
            data.put("temporary_condition_follow_up", temporaryConditionFollowUpList);
        }

        List<ProposalByCommericalAndMarketingVO> proposalByCommericalAndMarketingVOS = new ArrayList<>();
        List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketingList = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingByInstanceId(instanceId);
        if (proposalByCommericalAndMarketingList != null && proposalByCommericalAndMarketingList.size() > 0) {
            data.put("proposal_by_commerical_and_marketing", proposalByCommericalAndMarketingList);
        }

        List<SecuritieVO> securitieVOS = new ArrayList<>();
        List<Securities> securitieList = securitiesMapper.selectSecuritiesByInstanceId(instanceId);
        if (securitieList != null && securitieList.size() > 0) {
            data.put("securities", securitieList);
        }



        List<TemporaryConditionFollowUp> temporaryConditionFollowUp = temporaryConditionFollowUpMapper.selectTemporaryConditionFollowUpByInstanceId(instanceId);
        if (null != temporaryConditionFollowUp) {
            map.put("temporaryConditionFollowUp", temporaryConditionFollowUp);
        }

        DealerNegativeInformationCheck dealerNegativeInformationCheck = dealerNegativeInformationCheckService.selectDealerNegativeInformationCheckById(instanceId);
        if (null != dealerNegativeInformationCheck) {
            map.put("dealerNegativeInformationCheck", dealerNegativeInformationCheck);
        }

        Fileupload fileupload = new Fileupload();
        fileupload.setInstanceId(instanceId);
        fileupload.setType("application");
        List<Fileupload> application = fileuploadService.selectFileuploadList(fileupload);
        if (application != null) {
            map.put("application", application);
        }
        fileupload.setType("information");
        List<Fileupload> information = fileuploadService.selectFileuploadList(fileupload);
        if (information != null) {
            map.put("information", information);
        }
        fileupload.setType("financials");
        List<Fileupload> financials = fileuploadService.selectFileuploadList(fileupload);
        if (financials != null) {
            map.put("financials", financials);
        }
        fileupload.setType("guarantee");
        List<Fileupload> guarantee = fileuploadService.selectFileuploadList(fileupload);
        if (guarantee != null) {
            map.put("guarantee", guarantee);
        }
        fileupload.setType("corporate");
        List<Fileupload> corporate = fileuploadService.selectFileuploadList(fileupload);
        if (corporate != null) {
            map.put("corporate", corporate);
        }
        fileupload.setType("other");
        List<Fileupload> other = fileuploadService.selectFileuploadList(fileupload);
        if (other != null) {
            map.put("other", other);
        }
        fileupload.setType("financialAnalysis");
        List<Fileupload> financialAnalysis = fileuploadService.selectFileuploadList(fileupload);
        if (financialAnalysis != null) {
            map.put("financialAnalysis", financialAnalysis);
        }
        fileupload.setType("pboc");
        List<Fileupload> pboc = fileuploadService.selectFileuploadList(fileupload);
        if (pboc != null) {
            map.put("pboc", pboc);
        }
        fileupload.setType("lawsuit");
        List<Fileupload> lawsuit = fileuploadService.selectFileuploadList(fileupload);
        if (lawsuit != null) {
            map.put("lawsuit", lawsuit);
        }
        fileupload.setType("underwriterOther");
        List<Fileupload> underwriterOther = fileuploadService.selectFileuploadList(fileupload);
        if (underwriterOther != null) {
            map.put("underwriterOther", underwriterOther);
        }
        fileupload.setType("opDocument");
        List<Fileupload> opDocument = fileuploadService.selectFileuploadList(fileupload);
        if (opDocument != null) {
            map.put("opDocument", opDocument);
        }

        if (null == annualReviewy.getUsername()) {
            String username = SecurityUtils.getLoginUser().getUsername();
            annualReviewyMapper.closeUpdateAnnualReviewyObj(instanceId, username);
        }
        data.put("children", childrenList);

        Notes notes = notesMapper.selectNotesByInstanceId(instanceId);
        if (notes != null) {
            data.put("basicNotes", notes.getBasicNotes());
            data.put("dealerNotes", notes.getDealerNotes());
            data.put("loyaltyNotes", notes.getLoyaltyNotes());
            data.put("auditNotes", notes.getAuditNotes());
            data.put("wholesaleNotes", notes.getWholesaleNotes());
            data.put("proposalNotes", notes.getProposalNotes());
        }
        map.put("data", data);
        return map;
    }

    /**
     * 根据id查询，给邮箱模板返回需要的信息
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> selectMailInfoById(String id) {
        ApprovedLimitAndCondition approvedLimitAndCondition = approvedLimitAndConditionMapper.selectApprovedLimitAndConditionById(id);
        CreditCondition creditCondition = creditConditionMapper.selectCreditConditionById(id);
        BasicInformation basicInformation = basicInformationMapper.selectBasicInformationById(id);

        Map<String, Object> mailMap = new HashMap<>();
        mailMap.put("DealerNameEN", basicInformation.getDealerNameEN());
        mailMap.put("DealerNameCN", basicInformation.getDealerNameCN());
        mailMap.put("sector", basicInformation.getSector());
        mailMap.put("current_year", "");
        mailMap.put("limit", approvedLimitAndCondition.getLimittype());
        mailMap.put("deposit", approvedLimitAndCondition.getApprovedcashdeposit());
        mailMap.put("guarantee_structure", "");
        mailMap.put("approvedLimitAndCondition", approvedLimitAndCondition);
        mailMap.put("creditCondition", creditCondition);
        return mailMap;
    }

    @Override
    public Map<String, Object> selectMailInfo(Map<String, Object> map) {
        Map<String, Object> mailMap = new HashMap<>();
        mailMap.put("DealerNameEN", "basicInformation.getDealerNameEN()");
        mailMap.put("DealerNameCN", "basicInformation.getDealerNameCN()");
        mailMap.put("sector", "basicInformation.getSector()");
        mailMap.put("current_year", "");
        mailMap.put("limit", "approvedLimitAndCondition.getLimittype()");
        mailMap.put("deposit", "approvedLimitAndCondition.getCurrentsecurityratio()");
        mailMap.put("guarantee_structure", "");
        mailMap.put("approvedLimitAndCondition", "approvedLimitAndCondition");
        mailMap.put("creditCondition", "creditCondition");
        return mailMap;
    }

    @Override
    public Map<String, Object> selectMailInfoByInstanceId(String instanceId) {

        String sector = "byd";
        String dealerNameEN = "Dealer Name EN";
        String dealerNameCN = "Dealer Name CN";
        String currentYear = "byd";
        String limit = "5";
        String deposit = "10";
        String guaranteeStructure = "guarantee structure";

        StringBuilder table = new StringBuilder("<html ><body>");
        table.append("<table border=\"1\">\n");
        table.append("<tr>\n");
        table.append("<td rowspan=\"2\">Dealer Name</td>\n");
        table.append(" <td rowspan=\"2\">Brand</td>\n");
        table.append("<td rowspan=\"2\">Limit Type</td>\n");
        table.append("<td rowspan=\"2\">Active Limit</td>\n");
        table.append("<td rowspan=\"2\">OS</td>\n");
        table.append("<td colspan=\"2\">Current</td>\n");
        table.append("<td colspan=\"2\">Proposed</td>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("<td>Approved Limit</td>\n");
        table.append("<td>Deposit%</td>\n");
        table.append("<td>Approved Limit</td>\n");
        table.append("<td>Deposit%</td>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("<td rowspan=\"5\">Ningbo\n");
        table.append("<br>\n");
        table.append("Zhongxinbole\n");
        table.append("<br>\n");
        table.append("Auto\n");
        table.append("<br>\n");
        table.append("Sales&Service\n");
        table.append("<br>\n");
        table.append("Co., Ltd.</td>\n");
        table.append(" <td rowspan=\"2\">CKD</td>\n");
        table.append("<td>Normal</td>\n");
        table.append("<td>3,180,000</td>\n");
        table.append("<td>2,002,148</td>\n");
        table.append("<td>3,500,000</td>\n");
        table.append("<td rowspan=\"5\">15%</td>\n");
        table.append("<td>3,500,000</td>\n");
        table.append("<td rowspan=\"5\">15%</td>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("<td>Demo</td>\n");
        table.append("<td>150,000</td>\n");
        table.append("<td>145,703</td>\n");
        table.append("<td>1,000,000</td>\n");
        table.append("<td>1,000,000</td>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("<td rowspan=\"3\">BUX</td>\n");
        table.append("<td >Normal</td>\n");
        table.append("<td >7,200,000</td>\n");
        table.append("<td >4,768,000</td>\n");
        table.append("<td >7,200,000</td>\n");
        table.append("<td>7,200,000</td>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("<td rowspan=\"2\">Demo</td>\n");
        table.append("<td rowspan=\"2\">800,000</td>\n");
        table.append("<td rowspan=\"2\">693,645</td>\n");
        table.append("<td rowspan=\"2\">800,000</td>\n");
        table.append("<td rowspan=\"2\">800,000</td>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("<td>Total</td>\n");
        table.append("<td></td>\n");
        table.append("<td></td>\n");
        table.append("<td>11,330,000</td>\n");
        table.append("<td>7,609,495</td>\n");
        table.append("<td>12,500,000</td>\n");
        table.append("<td></td>\n");
        table.append("<td>12,500,000</td>\n");
        table.append("<td></td>\n");
        table.append("</tr>\n");
        table.append("</table></body></html>\n");
        String content = "Dear Committee,\n" +
                "\n" +
                "This is to seek your approval of " + sector + " dealer – " + dealerNameEN + " " + dealerNameCN + " " + currentYear + " annual review.\n" +
                "\n" +
                "As proposed by dealer and Sales team, we suggest to\n" +
                //"[根据workflow Approved Limit and Condition]\n" +
                "1)Maintain CKD limit of 4.5M and BUX limit of 8M;" + "[" + limit + "]\n" +
                "2)Maintain cash deposit ratio at 15%;[" + deposit + "%]\n" +
                "3)Maintain guarantee structure – Ningbo Bonded Port Fengzhe Investment and" +
                " Management Co., Ltd. (宁波梅山保税港区丰哲投资管理有限公司), Ye Wenjie (叶文杰) " +
                "and Wang Wei (王伟) [" + guaranteeStructure + "]\n" +
                "4)Special Approval:\n" +
                "\n" +
                "Basic information\n" +
                "[取workflow Approved Limit and Condition]\n" +
                table +
                "\n" +
                "Credit Comments:\n" +
                "[取workflow credit comments]\n" +
                "\n" +
                "Please find detailed information and analysis in annual review report.";


        Map<String, Object> mailMap = new HashMap<>();
        mailMap.put("to", "1404027183@qq.com");
        mailMap.put("title", "测试邮件发送内容格式225");
        mailMap.put("content", content);

        return mailMap;
    }

    @Override
    public int updateMain(Map<String, Object> map) {
        String parantInstanceId = "";
        Task task = taskService.createTaskQuery()
                .taskId(map.get("id")
                        .toString())
                .singleResult();
        List<HistoricDetail> historicDetails = SpringUtils.getBean(HistoryService.class)
                .createHistoricDetailQuery()
                .variableUpdates()
                .processInstanceId(task.getProcessInstanceId())
                .list();
        for (HistoricDetail historicDetail : historicDetails) {
            HistoricVariableUpdate historicVariableUpdate = (HistoricVariableUpdate) historicDetail;
            if ("parentId".equals(historicVariableUpdate.getVariableName())) {
                parantInstanceId = (String) historicVariableUpdate.getValue();
            }
        }

        DealerNegativeInformationCheck dealerNegativeInformationCheck = new DealerNegativeInformationCheck();
        dealerNegativeInformationCheck.setId(parantInstanceId);
        DealerNegativeInformationCheck flag = dealerNegativeInformationCheckService.selectDealerNegativeInformationCheckById(parantInstanceId);

        Object ishavenagetiveinformation = map.get("ishavenagetiveinformation");
        Object nagetiveinformationtext = map.get("nagetiveinformationtext");
        Object dmvisitandsubmit = map.get("dmvisitandsubmit");
        Object visitandsubmittext = map.get("visitandsubmittext");
        Object ishavestockauditissue = map.get("ishavestockauditissue");
        Object stockauditissuetext = map.get("stockauditissuetext");
        Object isgetcarsto4sshop = map.get("isgetcarsto4sshop");
        Object getcarsto4sshoptext = map.get("getcarsto4sshoptext");
        Object ishaveillegalparkingin3month = map.get("ishaveillegalparkingin3month");
        Object illegalparkingtext = map.get("illegalparkingtext");
        Object isabnormalsituation = map.get("isabnormalsituation");
        Object abnormalsituationtext = map.get("abnormalsituationtext");
        Object ishaveloanextension = map.get("ishaveloanextension");
        Object loanextensiontext = map.get("loanextensiontext");
        Object ispaidup = map.get("ispaidup");
        Object paiduptext = map.get("paiduptext");

        DealerNegativeInformationCheck dealerNegativeInformationCheckI = JSON.parseObject(JSON.toJSONString(map), DealerNegativeInformationCheck.class);
        dealerNegativeInformationCheckI.setInstanceId(String.valueOf(parantInstanceId));
        dealerNegativeInformationCheckI.setId(String.valueOf(parantInstanceId));
        if (null != ishavenagetiveinformation || (null != nagetiveinformationtext && !"".equals(nagetiveinformationtext)) || null != dmvisitandsubmit || (null != visitandsubmittext && !"".equals(visitandsubmittext))) {
            dealerNegativeInformationCheckI.setIsStartDM(false);
        }
        if (null != ishavestockauditissue || (null != stockauditissuetext && !"".equals(stockauditissuetext)) || null != isgetcarsto4sshop || (null != getcarsto4sshoptext && !"".equals(getcarsto4sshoptext)) || null != ishaveillegalparkingin3month || (null != illegalparkingtext && !"".equals(illegalparkingtext)) || null != isabnormalsituation || (null != abnormalsituationtext && !"".equals(abnormalsituationtext)) || null != ishaveloanextension || (null != loanextensiontext && !"".equals(loanextensiontext)) || null != ispaidup || (null != paiduptext && !"".equals(paiduptext))) {
            dealerNegativeInformationCheckI.setIsStartPLM(false);
        }
        if (null == flag) {
            dealerNegativeInformationCheckService.insertDealerNegativeInformationCheck(dealerNegativeInformationCheckI);
        } else {
            dealerNegativeInformationCheckService.updateDealerNegativeInformationCheck(dealerNegativeInformationCheckI);
        }
        return 1;
    }

    @Override
    public DealerNegativeInformationCheck getMain(String taskId) {
        String parantInstanceId = "";
        Task task = taskService.createTaskQuery()
                .taskId(taskId)
                .singleResult();
        List<HistoricDetail> historicDetails = SpringUtils.getBean(HistoryService.class)
                .createHistoricDetailQuery()
                .variableUpdates()
                .processInstanceId(task.getProcessInstanceId())
                .list();
        for (HistoricDetail historicDetail : historicDetails) {
            HistoricVariableUpdate historicVariableUpdate = (HistoricVariableUpdate) historicDetail;
            if ("parentId".equals(historicVariableUpdate.getVariableName())) {
                parantInstanceId = (String) historicVariableUpdate.getValue();
            }
        }
        DealerNegativeInformationCheck dealerNegativeInformationCheck = new DealerNegativeInformationCheck();
        dealerNegativeInformationCheck.setId(parantInstanceId);
        dealerNegativeInformationCheck = dealerNegativeInformationCheckService.selectDealerNegativeInformationCheckById(parantInstanceId);
        return dealerNegativeInformationCheck;
    }

    @Override
    public List<AnnualReviewyVO> selectAnnualReviewyVOList(AnnualReviewy annualReviewy) {
        String instanceId = annualReviewy.getInstanceId();
        List<AnnualReviewyVO> list = new ArrayList<>();
        AnnualReviewyVO annualReviewyVO = null;
        List<SalesPerformanceAndTarget> salesPerformanceAndTarget = salesPerformanceAndTargetMapper.selectSalesPerformanceAndTargetByInstanceId(instanceId);
        List<LimitCalculationForCommericalNeeds> limitCalculationForCommericalNeeds = limitCalculationForCommericalNeedsMapper.selectLimitCalculationForCommericalNeedsByInstanceId(instanceId);
        List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketing = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingByInstanceId(instanceId);
        List<OtherFinancingResource> otherFinancingResource = otherFinancingResourceMapper.selectOtherFinancingResourceByInstanceId(instanceId);
        List<Securities> securities = securitiesMapper.selectSecuritiesByInstanceId(instanceId);
        Notes notes = notesMapper.selectNotesByInstanceId(instanceId);

        if (salesPerformanceAndTarget != null && salesPerformanceAndTarget.size() > 0) {
            annualReviewyVO = new AnnualReviewyVO();
            annualReviewyVO.setSalesPerformanceAndTarget(salesPerformanceAndTarget);
        }

        if (limitCalculationForCommericalNeeds != null && limitCalculationForCommericalNeeds.size() > 0) {
            for (LimitCalculationForCommericalNeeds limitCalculationForCommericalNeed : limitCalculationForCommericalNeeds) {
                annualReviewyVO = new AnnualReviewyVO();
                annualReviewyVO.setLimitCalculationForCommericalNeeds(limitCalculationForCommericalNeed);
            }
        }

        if (proposalByCommericalAndMarketing != null && proposalByCommericalAndMarketing.size() > 0) {
            for (ProposalByCommericalAndMarketing byCommericalAndMarketing : proposalByCommericalAndMarketing) {
                annualReviewyVO = new AnnualReviewyVO();
                annualReviewyVO.setProposalByCommericalAndMarketing(byCommericalAndMarketing);
            }
        }

        if (otherFinancingResource != null && otherFinancingResource.size() > 0) {
            for (OtherFinancingResource financingResource : otherFinancingResource) {
                annualReviewyVO = new AnnualReviewyVO();
                annualReviewyVO.setOtherFinancingResource(financingResource);
            }
        }

        if (securities != null && securities.size() > 0) {
            for (Securities security : securities) {
                annualReviewyVO = new AnnualReviewyVO();
                annualReviewyVO.setSecurities(security);
            }
        }

        if (notes != null) {
            annualReviewyVO.setNotes(notes);
        }
        list.add(annualReviewyVO);
        return list;
    }

    //根据条件搜索
    @Override
    public Page<ActTaskDTO> selectProcessDefinitionSearchList(SearchVo searchVo, PageDomain pageDomain) {
        Page<ActTaskDTO> list = new Page<ActTaskDTO>();
        String authenticatedUserId = this.securityManager.getAuthenticatedUserId();
        if (authenticatedUserId != null && !authenticatedUserId.isEmpty()) {
            List<String> userGroups = this.userGroupManager.getUserGroups(authenticatedUserId);
            org.activiti.api.runtime.shared.query.Page<org.activiti.api.task.model.Task> pageTasks = this.tasks(Pageable.of((pageDomain.getPageNum() - 1) * pageDomain.getPageSize(), pageDomain.getPageSize()), TaskPayloadBuilder.tasks().withAssignee(authenticatedUserId).withGroups(userGroups).build(), searchVo);
            List<org.activiti.api.task.model.Task> tasks = pageTasks.getContent();
            int totalItems = pageTasks.getTotalItems();
            list.setTotal(totalItems);
            if (totalItems != 0) {
                Set<String> processInstanceIdIds = tasks.parallelStream().map(t -> t.getProcessInstanceId()).collect(Collectors.toSet());
                // List<AnnualReviewy> annualReviewies = annualReviewyMapper.selectAnnualReviewyByInstanceIds(new ArrayList<>(processInstanceIdIds));
                List<org.activiti.engine.runtime.ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery().processInstanceIds(processInstanceIdIds).list();
                Set<String> businessKeys = processInstanceList.parallelStream().map(t -> t.getBusinessKey()).collect(Collectors.toSet());
                List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByByInstanceIds(businessKeys);
                Set<String> userIds = processInstanceList.parallelStream().map(t -> t.getStartUserId()).collect(Collectors.toSet());
                List<Map> maps = userMapper.selectUsersByIds(userIds);
                List<ActTaskDTO> actTaskDTOS = tasks.stream().map(t -> {
                            ActTaskDTO actTaskDTO = new ActTaskDTO(t, processInstanceList.parallelStream().filter(pi ->
                                    t.getProcessInstanceId().equals(pi.getId())).findAny().get());
                            String startUserId = actTaskDTO.getStartUserId();
                            for (Map map : maps) {
                                if (map.get("user_id").toString().equals(startUserId)) {
                                    actTaskDTO.setAssignee(map.get("nick_name").toString());
                                }
                            }
                            for (BasicInformation basicInformation : basicInformations) {
                                if (basicInformation.getInstanceId().equals(actTaskDTO.getBusinessKey())) {
                                    if (null != basicInformation.getGroupNameCN() && !"".equals(basicInformation.getGroupNameCN())) {
                                        actTaskDTO.setDealerName(basicInformation.getGroupNameCN());
                                    } else {
                                        actTaskDTO.setDealerName(basicInformation.getDealerNameCN());
                                    }
                                }
                            }
                            return actTaskDTO;
                        })
                        .collect(Collectors.toList());
                list.addAll(actTaskDTOS);

            }

            return list;
        } else {
            throw new IllegalStateException("You need an authenticated user to perform a task query");
        }

    }

    @Override
    public CustomPage indexData() {
        CustomPage customPage = new CustomPage();
        String username = SecurityUtils.getUsername();
        int yfqNum = annualReviewyMapper.selectCountByCreatenameAndStatus(username, null);
        int jxzNum = annualReviewyMapper.selectCountByCreatenameAndStatus(username, "0");
        int ywcNum = annualReviewyMapper.selectCountByCreatenameAndStatus(username, "1");
        customPage.setYfqNum(yfqNum);
        customPage.setJxzNum(jxzNum);
        customPage.setYwcNum(ywcNum);
        long ybcount = historyService.createHistoricTaskInstanceQuery().taskAssignee(username).finished().count();
        customPage.setYclNum(ybcount);
        return customPage;
    }

    public org.activiti.api.runtime.shared.query.Page<org.activiti.api.task.model.Task> tasks(Pageable pageable, GetTasksPayload getTasksPayload, SearchVo searchVo) {
        TaskQuery taskQuery = this.taskService.createTaskQuery();
        if (getTasksPayload == null) {
            getTasksPayload = TaskPayloadBuilder.tasks().build();
        }

        String authenticatedUserId = this.securityManager.getAuthenticatedUserId();
        if (authenticatedUserId != null && !authenticatedUserId.isEmpty()) {
            List<String> tasks = this.userGroupManager.getUserGroups(authenticatedUserId);
            getTasksPayload.setAssigneeId(authenticatedUserId);
            getTasksPayload.setGroups(tasks);
            taskQuery = (TaskQuery) ((TaskQuery) ((TaskQuery) taskQuery.or()).taskCandidateOrAssigned(getTasksPayload.getAssigneeId(), getTasksPayload.getGroups()).taskOwner(authenticatedUserId)).endOr();
            if (getTasksPayload.getProcessInstanceId() != null) {
                taskQuery = (TaskQuery) taskQuery.processInstanceId(getTasksPayload.getProcessInstanceId());
            }

            if (getTasksPayload.getParentTaskId() != null) {
                taskQuery = (TaskQuery) taskQuery.taskParentTaskId(getTasksPayload.getParentTaskId());
            }
            boolean hasName = false;
            BasicInformation basicInformation = new BasicInformation();
            if (StringUtils.isNotBlank(searchVo.getGroupNameCN())) {
                basicInformation.setGroupNameCN(searchVo.getGroupNameCN());
                hasName = true;
            }
            if (StringUtils.isNotBlank(searchVo.getDealerNameCN())) {
                basicInformation.setDealerNameCN(searchVo.getDealerNameCN());
                hasName = true;
            }
            List<String> instanceIds = null;
            if (hasName) {
                List<BasicInformation> basicInformations = basicInformationMapper.selectBasicInformationList(basicInformation);
                instanceIds = basicInformations.parallelStream().map(t -> {
                    return t.getInstanceId();
                }).collect(Collectors.toList());
                List<String> processInstanceIdIds = new ArrayList<>();
                if (null != instanceIds && instanceIds.size() > 0) {
                    for (String instanceId : instanceIds) {
                        org.activiti.engine.runtime.ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(instanceId).singleResult();
                        processInstanceIdIds.add(processInstance.getProcessInstanceId());
                    }
                    if (null != processInstanceIdIds && 0 != processInstanceIdIds.size()) {
                        taskQuery.processInstanceIdIn(processInstanceIdIds);
                    } else {
                        return new PageImpl(new ArrayList<org.activiti.api.task.model.Task>(), 0);
                    }
                } else {
                    return new PageImpl(new ArrayList<org.activiti.api.task.model.Task>(), 0);
                }
            }

            /*if (StringUtils.isNotBlank(searchVo.getProcessName())) {
                List<org.activiti.engine.runtime.ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().processInstanceNameLike("%"+searchVo.getProcessName()+"%").list();
                List<String> processInstanceIdIds = processInstances.parallelStream().map(t -> t.getProcessInstanceId()).collect(Collectors.toList());
                if(null!=processInstanceIdIds&&0!=processInstanceIdIds.size()){
                    taskQuery.processInstanceIdIn(processInstanceIdIds);
                }else {
                    return new PageImpl(new ArrayList<org.activiti.api.task.model.Task>(),0);
                }
            }*/
            if (searchVo.getStartDate() != null) {
                taskQuery.taskCreatedAfter(searchVo.getStartDate());
            }
            if (searchVo.getEndDate() != null) {
                taskQuery.taskCreatedBefore(searchVo.getEndDate());
            }
            if ("createdDate".equals(searchVo.getOrderByColumn())) {
                if ("asc".equals(searchVo.getOrder())) {
                    taskQuery.orderByTaskCreateTime().asc();
                } else {
                    taskQuery.orderByTaskCreateTime().desc();
                }
            } else {
                taskQuery.orderByTaskCreateTime().desc();
            }

            List<org.activiti.api.task.model.Task> tasksRs = this.taskConverter.from(taskQuery.listPage(pageable.getStartIndex(), pageable.getMaxItems()));
            return new PageImpl(tasksRs, Math.toIntExact(taskQuery.count()));
        } else {
            throw new IllegalStateException("You need an authenticated user to perform a task query");
        }
    }


}
